<!-- 新建和编辑用户 -->
<template>
  <el-form class="app-container">
    <el-card
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      :header="form.userid?'编辑用户':'新建用户'"
      shadow="always"
    >
      <el-form class="form-container">
        <el-row>
          <el-col :span="24">
            <el-form :model="form" label-width="100px" :rules="formRules" ref="form">
              <el-form-item label="用户角色" prop="roles">
                <el-checkbox-group v-model="form.roles">
                  <el-checkbox
                    v-for="item in roleOptions.filter(role => {
                      return role.rolestatus == 1
                    })"
                    :key="item.roleid"
                    :label="item.roleid + ''"
                    :checked="checked"
                    @change="checked=!checked;roleschange()"
                  >{{item.rolename}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <div class="flex-input">
                <el-form-item style="width:45%" prop="loginphone" label="登录手机">
                  <el-input v-model="form.loginphone" clearable placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item style="width:45%" prop="userrealname" label="姓名">
                  <el-input v-model="form.userrealname" clearable placeholder="请输入用户姓名" />
                </el-form-item>
                <el-form-item
                  v-if="!form.userid"
                  style="width:45%"
                  prop="userrealname"
                  label="用户密码"
                >
                  <el-input v-model="form.userpassword" clearable placeholder="请输入用户密码" />
                </el-form-item>
                <el-form-item
                  v-if="form.userid"
                  style="width:100%"
                  prop="isChangePassword"
                  label="修改密码"
                >
                  <el-switch v-model="isChangePassword" active-text="开启" />
                </el-form-item>
                <el-form-item v-if="isChangePassword" style="width:45%" prop="password" label="密码">
                  <el-input type="password" v-model="form.password" clearable placeholder="请输入密码" />
                </el-form-item>
                <el-form-item
                  v-if="isChangePassword"
                  style="width:45%"
                  prop="repassword"
                  label="确认密码"
                >
                  <el-input
                    type="password"
                    v-model="form.repassword"
                    clearable
                    placeholder="请再次输入密码"
                  />
                </el-form-item>

                <el-form-item style="width:45%" prop="userstatus" label="用户状态">
                  <el-switch @change="handleStatusChange" :value="userStatus" active-text="启用" />
                </el-form-item>
              </div>
            </el-form>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end" style="margin-top:150px">
          <el-col :span="4">
            <el-button plain type="primary" @click="onSubmit">{{ form.userid?'确认更新':'确认添加' }}</el-button>
            <el-button @click="back">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </el-form>
</template>

<script>
export default {
  name: "userEdit",
  props: {
    form: {
      type: Object,
      default() {
        return {
          userid: "",
          loginphone: "",
          userpassword: "",
          userrealname: "",
          userstatus: "",
          roles: [],
          password: "",
          repassword: ""
        };
      }
    }
  },
  data() {
    // 表单规则
    const vaslidateEmpty = (rule, value, callback) => {
      if (value.trim()) {
        callback();
      } else {
        callback(new Error("该项内容不能为空"));
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入再次密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      checked: false,
      loading: false,
      disabled: true,
      roleOptions: [],
      departmentOptions: [],
      remarkOptions: [],
      isChangePassword: false,
      // 表单验证规则
      formRules: {
        loginphone: [
          { required: true, trigger: "blur", validator: vaslidateEmpty }
        ],
        userrealname: [
          { required: true, trigger: "blur", validator: vaslidateEmpty }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePass }
        ],
        repassword: [
          { required: true, trigger: "blur", validator: validatePass2 }
        ]
      }
    };
  },
  computed: {
    userStatus() {
      return this.form.userstatus === "1";
    }
  },
  mounted() {
    this.getAllRoles();
    //console.log(this.form);
  },
  watch: {
    "form.userid": {
      handler(newval, oldval) {
        // console.log(this.isChangePassword);
        this.$nextTick(() => {
          this.isChangePassword = false;
        });
      }
    },
    $route: {
      handler(to, from) {
        Promise.all([this.fetchData(), this.getAllRoles()]);
      },
      deep: true
    }
  },
  methods: {
    switchChange() {
      // console.log(this.isChangePassword);
    },
    roleschange() {
      //console.log(this.form.roles);
    },
    back() {
      this.$emit("closeDialog");
    },
    handleChangeDate(val) {
      this.form.userbirthday = formatEasyTime(val);
    },
    async getAllRoles() {
      await this.$api
        .get(
          "http://139.9.249.149:8081/judge/role/all",
          {},
          { autoAlert: false, returnAll: true }
        )
        .then(res => {
          //console.log(res);
          this.roleOptions = res.data.msg;
        });
    },

    //用户状态改变时修改的switch
    handleStatusChange(val) {
      if (val) {
        this.form.userstatus = "1";
      } else {
        this.form.userstatus = "0";
      }
    },
    //提交时
    onSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            // 通过id判断时编辑还是更新
            this.loading = true;
            let res = null;
            if (this.form.userid) {
              if (this.form.password !== "") {
                //console.log("修改密码");
                this.form.userpassword = this.form.password;
              }

              res = await this.$api.put(
                `http://139.9.249.149:8081/judge/user`,
                {
                  userid: this.form.userid,
                  loginphone: this.form.loginphone,
                  userpassword: this.form.userpassword,
                  userrealname: this.form.userrealname,
                  userstatus: this.form.userstatus,
                  roles: this.form.roles.join(",")
                },
                { autoAlert: false, returnAll: true }
              );
            } else {
              res = await this.$api.post(
                `http://139.9.249.149:8081/judge/user`,
                {
                  userid: this.form.userid,
                  loginphone: this.form.loginphone,
                  userpassword: this.form.userpassword,
                  userrealname: this.form.userrealname,
                  userstatus: this.form.userstatus,
                  roles: this.form.roles.join(",")
                },
                { autoAlert: false, returnAll: true }
              );
            }
            if (+res.code === 200) {
              this.loading = false;
              this.$emit("fetchData");
              this.back();
            } else {
              this.$message.error(res.data.data.msg || "更新失败");
            }
          } catch (err) {
            this.$message.error("更新失败");
          }
        } else {
          this.$message.error("请检查表单是否输入正确");
          return false;
        }
      });
    }
  }
};
</script>
<style lang='stylus' scoped>
.app-container {
  .form-container {
    .tip {
      font-size: 12px;
      color: #a7a7af;
    }

    .flex-input {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding-right: 40px;
    }
  }
}
</style>
